import datetime
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

# ChromeIns=ChromeDriverManager().install()
# driver=webdriver.Chrome(service=Service(ChromeIns))
driver=webdriver.Chrome()
driver.get("https://www.baidu.com/")

# 1、id选择器->子类选择器
# ret=driver.find_elements(By.CSS_SELECTOR,"#hotsearch-content-wrapper > li")
# for i in ret:
#     print(i.text) # 获取文本获取的内容

# 2、操作测试对象
# ## 模拟按键输入
# driver.find_element(By.CSS_SELECTOR,"#chat-textarea").send_keys("你好")
# sleep(2)
# ## 点击
# # ele = driver.find_element(By.CSS_SELECTOR,"#chat-submit-button")
# # ele.click()
# driver.find_element(By.CSS_SELECTOR,"#chat-submit-button").click()
# sleep(4)
# ## 清除后，再输入并点击
# driver.find_element(By.CSS_SELECTOR,"#chat-textarea").clear()
# sleep(2)
# driver.find_element(By.CSS_SELECTOR,"#chat-textarea").send_keys("大梦想")
# driver.find_element(By.CSS_SELECTOR,"#chat-submit-button").click()
# sleep(2)

# ## 获取文本信息并用断言判断
# text=driver.find_element(By.CSS_SELECTOR,"#hotsearch-content-wrapper > li:nth-child(3) > a > span.title-content-title").text
# print(text)
# assert text == "实锤！“传说机型”歼-6无人机现身"
# ## 获取属性的值
# text1=driver.find_element(By.CSS_SELECTOR,"#chat-submit-button").get_attribute("id")
# print(text1)
# assert text1 == "chat-submit-button"
# title=driver.title
# url=driver.current_url
# print(title)
# print(url)

# 3、窗口
# ## 切换窗口
# ## 如果没有出现新标签页，那么跳转url后当前句柄也会指向这个url
# print("before:"+driver.title)
# print("before:"+driver.current_url)
# # 跳转到百度图片
# driver.find_element(By.CSS_SELECTOR,"#s-top-left > a:nth-child(6)").click()
# # 获取当前页面句柄 -- 第一个标签页
# curHandle=driver.current_window_handle
# # 获取所有句柄并遍历
# allHandles=driver.window_handles
# for handle in allHandles:
#     if handle!=curHandle:
#         # 切换句柄
#         driver.switch_to.window(handle)
# print("after:"+driver.title)
# print("after:"+driver.current_url)

# ## 设置窗口大小
# sleep(2)
# driver.maximize_window()  # 最大化
# sleep(2)
# driver.minimize_window()  # 最小化
# sleep(2)
# driver.fullscreen_window()  # 全屏
# sleep(2)
# driver.set_window_size(1024,800)    # 手动设置尺寸
# sleep(2)

## 屏幕截图
# # 添加屏幕截图，如果带有路径，要确保路径存在
# filename="./image/test.png"
# driver.save_screenshot(filename)
# 用带有时间戳的命名格式，防止出现同名图片名称覆盖历史图片
# 文件名不能包含空格，所以用strftime按照格式进行格式化
filename="autotest-"+datetime.datetime.now().strftime("%Y%m%d-%H%M%S")+".png"
driver.save_screenshot("./image/"+filename)

## 关闭窗口
driver.find_element(By.CSS_SELECTOR,"#s-top-left > a:nth-child(6)").click()
sleep(2)
# 退出一个窗口，关闭的是driver指向的对象
driver.close()
sleep(2)

# 退出浏览器，所有标签页都会关闭
driver.quit()